package com.examstack.common.util.email.impl;

import com.examstack.common.domain.email.Mail;
import com.examstack.common.util.PropertyUtil;
import com.examstack.common.util.email.JavaMailservice;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class JavaMailServiceImpl implements JavaMailservice {
    /**
     * 发送邮件
     * @param content 邮件内容
     * @param toEmail 接收邮件的邮箱
     * @return
     */
    @Override
    public boolean sendMail(String content, String toEmail){
        if (content == null || content.isEmpty()){ return false;}
        if (toEmail == null || toEmail.isEmpty()){ return false;}
        Mail mail = new Mail();
        mail.setContent(content);
        mail.setToMail(toEmail);
        Properties mailProp = PropertyUtil.initNewProp("mail.properties");
        mail.setFromMail(mailProp.getProperty("mail.fromEmail"));
        mail.setAccreditPwd(mailProp.getProperty("mail.accreditPwd"));
        mail.setMailSMTPHost(mailProp.getProperty("mail.mailSMTPHost"));
        mail.setFromNickName(mailProp.getProperty("mail.fromNickName"));
        mail.setSubject(mailProp.getProperty("mail.codeSubject"));
        String smtpPort = mailProp.getProperty("mail.smtpPort");
        if (smtpPort == null || smtpPort.trim().isEmpty()) {
            mail.setSmtpPort("25");
        } else {
            mail.setSmtpPort(smtpPort);
        }
        return this.sendEmail(mail);
    }

    /**
     * 发送完整邮件（不验证传参）
     * @param mail
     * @return 发送成功：true，发送失败：false
     */
    private boolean sendEmail(Mail mail) {
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();//SSL加密
            sf.setTrustAllHosts(true);
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", mail.getMailSMTPHost());
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
            final String smtpPort = mail.getSmtpPort();
            if (null !=  smtpPort && !smtpPort.isEmpty()){
                /* SSL加密则启用以下代码，不加密则不需要启用*/
                if (smtpPort.equals("465") || smtpPort.equals("587")){
                    props.setProperty("mail.smtp.port", smtpPort);
                    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                    props.setProperty("mail.smtp.socketFactory.fallback", "false");
                    props.setProperty("mail.smtp.socketFactory.port", smtpPort);
                }
            }
            Session session = Session.getInstance(props);
            session.setDebug(true);
            MimeMessage message = createMimeMessage(session, mail);
            Transport transport = session.getTransport();
            //若有错误，错误原因都在log已说明。
            transport.connect(mail.getFromMail(), mail.getAccreditPwd());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建一封只包含文本的简单邮件
     * @param session 和服务器交互的会话
     * @param mail
     * @return
     * @throws Exception
     */
    private MimeMessage createMimeMessage(Session session, Mail mail) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);
        // 2. From: 发件人
        message.setFrom(new InternetAddress(mail.getFromMail(), mail.getFromNickName(), "UTF-8"));
        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        String toNickName = mail.getToNickName() == null ? mail.getToNickName() : mail.getToMail();
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mail.getToMail(), toNickName, "UTF-8"));
        // 4. Subject: 邮件主题
        message.setSubject(mail.getSubject(), "UTF-8");
        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(mail.getContent(), "text/html;charset=UTF-8");
        // 6. 设置发件时间
        message.setSentDate(new Date());
        // 7. 保存设置
        message.saveChanges();
        return message;
    }


}
